Imports ReportServerWebService
Imports System.Text
Imports System.Security.Permissions

<Assembly: UIPermission(SecurityAction.RequestOptional, Unrestricted:=True)> 
<Assembly: Net.WebPermission(SecurityAction.RequestMinimum, Unrestricted:=True)> 
<Assembly: EnvironmentPermission(SecurityAction.RequestMinimum, Read:="USERNAME")> 
<Assembly: SecurityPermission(SecurityAction.RequestMinimum, Assertion:=True)> 


Public Class UI
    Dim rs As ReportServerWebService.ReportingServicesWebService.ReportingService2005
    Dim BaseList() As ReportServerWebService.ReportingServicesWebService.Job
    Dim UIModeMinimised As Boolean = False


    <EnvironmentPermission(SecurityAction.PermitOnly, Read:="USERNAME")> _
    <EnvironmentPermission(SecurityAction.Demand, Read:="USERNAME")> _
    Private Sub InstatiateWebService()
        Try
            rs = New ReportServerWebService.ReportingServicesWebService.ReportingService2005
            rs.Url = My.Settings.ReportServerWebService
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials
        Catch e As Exception
            Throw e
        End Try
    End Sub

   
    Private Function LoadWebServiceJobsForPolling() As ReportServerWebService.ReportingServicesWebService.Job()
        Dim Jobs() As ReportServerWebService.ReportingServicesWebService.Job = Nothing
        Try
            Dim WebPermission As System.Net.WebPermission = New System.Net.WebPermission(System.Net.NetworkAccess.Connect, New System.Text.RegularExpressions.Regex(rs.Url))
            WebPermission.PermitOnly()
            Jobs = rs.ListJobs
            WebPermission.RevertPermitOnly()
        Catch ex As Exception
            'If there was an error, dont allow polling to start
            Throw ex
        End Try
        Return Jobs
    End Function

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub CompareJobLists(ByVal FirstList() As ReportServerWebService.ReportingServicesWebService.Job, ByVal SecondList() As ReportServerWebService.ReportingServicesWebService.Job)
        Dim job As ReportServerWebService.ReportingServicesWebService.Job
        Dim blnStillRunning As Boolean = False
        Dim blnNewJob As Boolean = True

        For Each job In FirstList
            'if still in the second list then still running
            For Each secondlistjob As ReportServerWebService.ReportingServicesWebService.Job In SecondList
                If job.JobID = secondlistjob.JobID Then
                    blnStillRunning = True
                End If
            Next
            If blnStillRunning = False Then
                'Job has finished
                Me.bgPollForChange.ReportProgress(0, "Job [" & job.Name & "] has finished")
            End If
        Next

        For Each job In SecondList
            'if job is not in first list then it must be new!
            For Each firstlistjob As ReportServerWebService.ReportingServicesWebService.Job In FirstList
                If job.JobID = firstlistjob.JobID Then
                    blnNewJob = False
                End If
            Next

            If blnNewJob = True Then
                'Job is new
                Me.bgPollForChange.ReportProgress(0, "Job [" & job.Name & "] started at " & job.StartDateTime & " by " & job.User)
            End If
        Next

    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim envPermissions As EnvironmentPermission = New EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")
        envPermissions.Assert()

        Try
            InstatiateWebService()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            Security.CodeAccessPermission.RevertAssert()
        End Try

        Me.Timer1.Interval = My.Settings.PollTime
        Me.lblServer.Text = "Using: " & rs.Url
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    <UIPermission(SecurityAction.Demand, Unrestricted:=True)> _
    Private Sub bgPollForChange_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgPollForChange.DoWork
        'Get a new list and compare it to the base list
        Try
            Dim WebPermission As System.Net.WebPermission = New System.Net.WebPermission(System.Net.NetworkAccess.Connect, New System.Text.RegularExpressions.Regex(rs.Url))
            WebPermission.Assert()
            Dim NewList() As ReportServerWebService.ReportingServicesWebService.Job = LoadWebServiceJobsForPolling()
            Security.CodeAccessPermission.RevertAssert()
            CompareJobLists(BaseList, NewList)
            BaseList = NewList
        Catch ex As Exception
            Me.bgPollForChange.ReportProgress(-1, ex.Message)
        End Try

    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    <UIPermission(SecurityAction.Demand, Unrestricted:=True)> _
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Me.bgPollForChange.IsBusy = False Then
            Me.bgPollForChange.RunWorkerAsync()
            If Me.ProgressBar1.Value = Me.ProgressBar1.Maximum Then
                Me.ProgressBar1.Value = 0
            Else
                Me.ProgressBar1.PerformStep()
            End If
        Else
            'Debug.WriteLine("Worker not started this time - already working")
        End If
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    <UIPermission(SecurityAction.Demand, Unrestricted:=True)> _
    Private Sub StartPollingClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartPoll.Click, StartPollingToolStripMenuItem.Click
        Try

            Dim WebPermission As System.Net.WebPermission = New System.Net.WebPermission(System.Net.NetworkAccess.Connect, New System.Text.RegularExpressions.Regex(rs.Url))
            WebPermission.Assert()
            Try
                BaseList = LoadWebServiceJobsForPolling()
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally
                Security.CodeAccessPermission.RevertAssert()
            End Try

            Me.ProgressBar1.Visible = True
            Timer1.Enabled = True
            Me.btnStopPoll.Enabled = True
            Me.btnStartPoll.Enabled = False
            Me.NotifyIcon1.Text = "RSJM: watching. " & BaseList.Length & " reports running"
            Me.txtStatus.Text = "Polling for reporting activity started:" + Environment.NewLine
        Catch ex As Exception
            'don't allow polling to start
            Timer1.Enabled = False
            MsgBox(ex.Message, MsgBoxStyle.Critical & MsgBoxStyle.OkOnly, "Error connecting to web service")
        End Try
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub StopPollingClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStopPoll.Click, StopPollingToolStripMenuItem.Click
        Timer1.Enabled = False
        Me.btnStopPoll.Enabled = False
        Me.btnStartPoll.Enabled = True
        Me.ProgressBar1.Visible = False
        Me.NotifyIcon1.Text = "RSJM: not watching"
        Me.txtStatus.Text = Me.txtStatus.Text + Environment.NewLine + "Polling stopped."
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    <UIPermission(SecurityAction.Demand, Unrestricted:=True)> _
    Private Sub bgPollForChange_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgPollForChange.ProgressChanged
        ' Debug.WriteLine(CType(e.UserState, String))

        If e.ProgressPercentage = -1 Then
            'An error was thrown. Stop everything!
            Me.txtStatus.Text = CType(e.UserState, String)
            StopPollingClick(sender, e)
        Else
            Me.txtStatus.Text = Me.txtStatus.Text + Environment.NewLine + Now.ToShortTimeString + ": " + CType(e.UserState, String)

            If Me.SuppressBaloonsToolStripMenuItem.Checked = False Then
                Me.NotifyIcon1.BalloonTipText = CType(e.UserState, String)
                Me.NotifyIcon1.BalloonTipTitle = "RSJM: Job Activity"
                Me.NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
                Me.NotifyIcon1.ShowBalloonTip(200)
            End If
        End If
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        If Me.UIModeMinimised = True Then
            Me.Show()
            Me.UIModeMinimised = False
        End If
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub btnMinimise_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MinimiseToTrayToolStripMenuItem.Click
        Me.UIModeMinimised = True
        Me.Hide()
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub SuppressBaloonsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SuppressBaloonsToolStripMenuItem.Click
        Me.SuppressBaloonsToolStripMenuItem.Checked = Not Me.SuppressBaloonsToolStripMenuItem.Checked
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub SettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
        Dim settings As New Settings
        If settings.ShowDialog = Windows.Forms.DialogResult.OK Then
            'update config
            Try

                If (Not settings.txtRSWebService.Text = My.Settings.ReportServerWebService) Or _
             (Not (CInt(settings.txtPollTime.Text) * 1000) = My.Settings.PollTime) Then
                    My.Settings.ReportServerWebService = settings.txtRSWebService.Text
                    My.Settings.PollTime = CInt(settings.txtPollTime.Text) * 1000
                    Me.Timer1.Interval = My.Settings.PollTime
                    RestartPolling()
                End If
            Catch ex As Exception
                MsgBox("Settings couldn't be saved." & Environment.NewLine & ex.Message, MsgBoxStyle.Critical, "RSJM Settings")
            End Try
        End If
    End Sub

    <UIPermission(SecurityAction.PermitOnly, Unrestricted:=True)> _
    Private Sub RestartPolling()
        Dim blnPollWasRunning As Boolean = Me.Timer1.Enabled

        If blnPollWasRunning Then
            Me.Timer1.Enabled = False
        End If

        Try
            rs.Dispose()
            rs = Nothing
            
            Dim envPermissions As EnvironmentPermission = New EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")
            envPermissions.Assert()

            Try
                InstatiateWebService()
                Me.lblServer.Text = "Using: " & rs.Url
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally
                Security.CodeAccessPermission.RevertAssert()
            End Try

            If blnPollWasRunning Then
                Me.txtStatus.Text = Me.txtStatus.Text + Environment.NewLine + Environment.NewLine + "Settings Updated. URL: [" + rs.Url + "] Poll Time: " + CInt(My.Settings.PollTime / 1000).ToString + " secs" + Environment.NewLine
                Me.Timer1.Enabled = True
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try



    End Sub


    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim about As New AboutBox
        about.ShowDialog()
    End Sub
End Class

